#include "driver.h"


NTSTATUS
DDAttachDevice(IN PDEVICE_OBJECT device, IN PDRIVER_OBJECT driver) {
	PDEVICE_OBJECT new_device;
	PDD_DEVICE new_device_ex;
	NTSTATUS ntStatus = STATUS_SUCCESS;
	ULONG i;
	for (i = 0; i < MAX_ATTACHED_DEVICES_COUNT; ++i)
		if (AttachedDevices[i] == device)
			return STATUS_SUCCESS;

	for (i = 0; i < MAX_ATTACHED_DEVICES_COUNT; ++i)
		if (AttachedDevices[i] == NULL)
			break;

	if (i == MAX_ATTACHED_DEVICES_COUNT) {
		DbgMess(("Cannot attach extra device"));
		return STATUS_INVALID_DEVICE_REQUEST;
	}

	DbgMess(("Creating device"));

	ntStatus = IoCreateDevice(
		driver,
		sizeof(DD_DEVICE),
		NULL,
		device->DeviceType,
		0,
		FALSE,
		&new_device);


	if (!(NT_SUCCESS(ntStatus))) {
		DbgMess(("Cannot create device object for 0x%x", device));
		IoDeleteDevice(new_device);
		return ntStatus;
	}

	DbgMess(("device created: %X", new_device));

	new_device_ex = new_device->DeviceExtension;

	new_device_ex->GuiInterface = FALSE;

	new_device_ex->fdo = new_device;

	new_device_ex->FileSystem = device;

	DbgMess(("device is attaching"));
	new_device_ex->FileSystem = IoAttachDeviceToDeviceStack(new_device, device);

	if (new_device_ex->FileSystem == NULL) {
		DbgMess(("Cannot attach device: %x", ntStatus));

		IoDeleteDevice(new_device);

		return STATUS_INVALID_DEVICE_REQUEST;
	}

	DbgMess(("device is attached: 0x%x", new_device_ex->FileSystem));
	AttachedDevices[i] = new_device;

	return ntStatus;
}